﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Collections.Generic;

public partial class Admin_Statistics : System.Web.UI.Page
{
    StatisticsBLL statsLogic = new StatisticsBLL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

        }
    }

    protected void btnOpenLoginStats_Click(object sender, EventArgs e)
    {
        txtLoginEndDate.Text = DateTime.Now.ToString("MM/dd/yyyy");
        txtLoginStartDate.Text = DateTime.Now.AddDays(-1).ToString("MM/dd/yyyy");
        PanelLoginStats.Visible = true;
        PanelQuizStats.Visible = false;
        PanelLearnObjStats.Visible = false;
    }

    protected void btnOpenLearnObjStats_Click(object sender, EventArgs e)
    {
        PanelLoginStats.Visible = false;
        PanelQuizStats.Visible = false;
        PanelLearnObjStats.Visible = true;
    }

    protected void btnLoginSearch_Click(object sender, EventArgs e)
    {
        ObjectDataSourceLoginResults.DataBind();
        GridViewLoginResults.DataBind();
        PanelLoginResults.Visible = true;
    }

    protected void btnOpenQuizStats_Click(object sender, EventArgs e)
    {
        LoadQuizStats();
        PanelQuizStats.Visible = true;
        PanelLoginStats.Visible = false;
        PanelLearnObjStats.Visible = false;
    }

    private void LoadQuizStats()
    {
        return;
    }

    protected void btnLoginExportToExcel_Click(object sender, EventArgs e)
    {
        ExportLoginStatsToExcel();
    }

    private void ExportLoginStatsToExcel()
    {
        string AccountType = ddlistLoginAccountType.SelectedValue.ToString();
        string NetworkID = txtLoginNetworkID.Text;
        DateTime StartTime = Convert.ToDateTime(txtLoginStartDate.Text);
        DateTime EndTime = Convert.ToDateTime(txtLoginEndDate.Text);

        GridViewLoginResults.PageSize = 5000;

        string fileName = "Login Stats - " + StartTime.ToShortDateString() + "~" + EndTime.ToShortDateString() + ".xls";

        string quizGrades = "attachment;filename=\"" + fileName + "\"";

        Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition", quizGrades);
        Response.ContentType = "application/ms-excel";

        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        GridViewLoginResults.AllowSorting = false;
        GridViewLoginResults.AllowPaging = false;
        GridViewLoginResults.GridLines = GridLines.Both;
        GridViewLoginResults.DataBind();

        //Change the Header Row back to white color
        GridViewLoginResults.HeaderRow.Style.Add("background-color", "#FFFFFF");


        //Apply style to Individual Cells
        for (int i = 0; i <= 5; i++)
        {
            GridViewLoginResults.HeaderRow.Cells[i].Style.Add("background-color", "#5D7B9D");
            GridViewLoginResults.HeaderRow.Cells[i].Style.Add("font-weight", "Bold");
            GridViewLoginResults.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");
            GridViewLoginResults.HeaderRow.Cells[i].Style.Add("height", "25px");
        }

        for (int i = 0; i < GridViewLoginResults.Rows.Count; i++)
        {
            GridViewRow row = GridViewLoginResults.Rows[i];

            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;

            //Apply text style to each Row
            //row.Attributes.Add("class", "textmode");

            //Apply style to Alternating Row
            if (i % 2 != 0)
            {
                for (int j = 0; j <= 5; j++)
                {
                    row.Cells[j].Style.Add("background-color", "#DDDDDD");
                }
            }

            row.Cells[0].Attributes.Add("class", "textmode");
            row.Cells[1].Attributes.Add("class", "textmode");
            row.Cells[2].Attributes.Add("class", "textmode");
            row.Cells[3].Attributes.Add("class", "datetimemode");
            row.Cells[4].Attributes.Add("class", "datetimemode");
            row.Cells[5].Attributes.Add("class", "textmode");
        }

        // This line was causing some error and That's why this page's 'EnabledEventValidation' property set to "False"
        GridViewLoginResults.RenderControl(htmlWrite);

        //style to format numbers to string
        string style = "<style> .textmode { mso-number-format:\\@; } .percentmode { mso-number-format: Percent; } .datetimemode { mso-number-format: \" mm\\/dd\\/yyyy hh:mm:ss AM\\/PM\" } </style>";
        Response.Write(style);
        Response.Output.Write(stringWrite.ToString());
        Response.Flush();
        Response.End();

        GridViewLoginResults.PageSize = 200;
    }

    /// <summary>
    /// This function is referenced from
    /// http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp2_dc11032006003657AM/exportxl_asp2_dc.aspx?ArticleID=000c64fb-8a22-414a-8247-984335aaa0eb
    /// </summary>
    /// <param name="control"></param>
    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
    }

    protected void GridViewLearnObjStatsCourseList_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView grdview = ((GridView)sender);
        if (grdview.SelectedIndex != -1)
        {
            FillSections((int)grdview.SelectedValue, ref ddlistSections);
            PanelLearnObjStatsSections.Visible = true;
            PanelLearnObjStatsLearnObjs.Visible = false;
            PanelLearnObjStatsLearnObjsList.Visible = false;
        }
        else
        {
            PanelLearnObjStatsSections.Visible = false;
        }
    }

    private void FillSections(int CourseID, ref DropDownList ddlist)
    {
        ClassBLL classLogic = new ClassBLL();
        Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, false);
        ddlist.Items.Clear();
        ddlist.Items.Add(new ListItem("--- Select a Section ---", "0"));
        foreach (Classes.Courses_SectionRow section in sections)
        {
            ListItem item = new ListItem();
            item.Text = section.SectionNumber.ToString();
            item.Value = section.SectionNumber.ToString();

            ddlist.Items.Add(item);
        }
    }

    protected void ddlistSections_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateRepeaterLearnObj();
    }

    private void UpdateRepeaterLearnObj()
    {
        int CourseID = Convert.ToInt32(GridViewLearnObjStatsCourseList.SelectedValue);
        int SectionNumber = Convert.ToInt32(ddlistSections.SelectedValue);
        int StandardID = Convert.ToInt32(RadioButtonListStandardID.SelectedValue);

        if (SectionNumber == null || SectionNumber == 0)
        {
            PanelLearnObjStatsLearnObjs.Visible = false;
            return;
        }

        //int[] LearnObjIDs = new int[20];
        List<int> LearnObjIDs = new List<int>();
        //int i = 0;

        ClassStandardsBLL classStandardLogic = new ClassStandardsBLL();
        ClassStandards.Courses_Standard_SectionRow section = classStandardLogic.GetClassSectionStandard(CourseID, SectionNumber, StandardID);
        if (section != null)
        {

            if (section.UseSectionInfo == true)
            {
                ClassStandards.Courses_LearnObj_SectionDataTable sectionLearnObjs = classStandardLogic.GetClassSectionLearnObjs(CourseID, SectionNumber, StandardID);
                foreach (ClassStandards.Courses_LearnObj_SectionRow sectionLearnObj in sectionLearnObjs)
                {
                    LearnObjIDs.Add(sectionLearnObj.LearnObjID);
                }
            }
            else
            {
                ClassStandards.Courses_LearnObjDataTable learnObjs = classStandardLogic.GetClassLearnObjs(CourseID, StandardID);
                foreach (ClassStandards.Courses_LearnObjRow learnObj in learnObjs)
                {
                    LearnObjIDs.Add(learnObj.LearnObjID);
                }
            }
        }
        else
        {
            ClassStandards.Courses_LearnObjDataTable learnObjs = classStandardLogic.GetClassLearnObjs(CourseID, StandardID);
            foreach (ClassStandards.Courses_LearnObjRow learnObj in learnObjs)
            {
                LearnObjIDs.Add(learnObj.LearnObjID);
            }
        }

        if (LearnObjIDs.Count == 0)
        {
            lblNoLearnObj.Visible = true;
        }
        else
        {
            lblNoLearnObj.Visible = false;
        }

        RepeaterLearningObj.DataSource = LearnObjIDs;
        RepeaterLearningObj.DataBind();

        PanelLearnObjStatsLearnObjsList.Visible = false;

        PanelLearnObjStatsLearnObjs.Visible = true;
    }

    protected void RadioButtonListStandardID_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateRepeaterLearnObj();
    }

    protected void RepeaterLearningObj_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            int row = Convert.ToInt32(e.Item.DataItem);

            LinkButton Title = e.Item.FindControl("lnkbtnSelectLearningObj") as LinkButton;
            LearnObjsBLL learnObjLogic = new LearnObjsBLL();

            Title.Text = learnObjLogic.GetLearnObj(row).Title;
            Title.CommandArgument = row.ToString();
        }
    }

    protected void lnkbtnSelectLearningObj_Click(object sender, CommandEventArgs e)
    {
        ddlistSelectedLearnObjID.Items.Clear();
        ddlistSelectedLearnObjID.Items.Add(new ListItem(Convert.ToInt32(e.CommandArgument).ToString()));
        ddlistSelectedLearnObjID.SelectedIndex = 0;

        ObjectDataSourceStatsLearnObjs.DataBind();
        GridViewStatsLearnObjs.DataSourceID = "ObjectDataSourceStatsLearnObjs";
        GridViewStatsLearnObjs.DataBind();

        if (GridViewStatsLearnObjs.Rows.Count == 0)
            btnLearnObjStatsExportToExcel.Visible = false;
        else
            btnLearnObjStatsExportToExcel.Visible = true;

        lblLearnObjStatsSelectedLearnObj.Text = ((LinkButton)sender).Text;
        PanelLearnObjStatsLearnObjsList.Visible = true;
    }


    protected void btnLearnObjStatsExportToExcel_Click(object sender, EventArgs e)
    {
        ExportLearnObjStatsStatsToExcel();
    }

    private void ExportLearnObjStatsStatsToExcel()
    {
        ClassBLL classLogic = new ClassBLL();

        string CourseTitle = classLogic.GetCourse(Convert.ToInt32(GridViewLearnObjStatsCourseList.SelectedValue)).Title;
        GridViewStatsLearnObjs.PageSize = 5000;
        //GridViewLoginResults.PageSize = 5000;

        string fileName = "Learning Object Stats - " + CourseTitle + " Sect. " + ddlistSections.SelectedValue.ToString() + ".xls";

        string learnObj = "attachment;filename=\"" + fileName + "\"";

        Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition", learnObj);
        Response.ContentType = "application/ms-excel";

        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        GridViewStatsLearnObjs.AllowSorting = false;
        GridViewStatsLearnObjs.AllowPaging = false;
        GridViewStatsLearnObjs.GridLines = GridLines.Both;
        GridViewStatsLearnObjs.DataBind();

        //Change the Header Row back to white color
        GridViewStatsLearnObjs.HeaderRow.Style.Add("background-color", "#FFFFFF");


        //Apply style to Individual Cells
        for (int i = 0; i <= 3; i++)
        {
            GridViewStatsLearnObjs.HeaderRow.Cells[i].Style.Add("background-color", "#5D7B9D");
            GridViewStatsLearnObjs.HeaderRow.Cells[i].Style.Add("font-weight", "Bold");
            GridViewStatsLearnObjs.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");
            GridViewStatsLearnObjs.HeaderRow.Cells[i].Style.Add("height", "25px");
        }

        for (int i = 0; i < GridViewStatsLearnObjs.Rows.Count; i++)
        {
            GridViewRow row = GridViewStatsLearnObjs.Rows[i];

            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;

            //Apply text style to each Row
            //row.Attributes.Add("class", "textmode");

            //Apply style to Alternating Row
            if (i % 2 != 0)
            {
                for (int j = 0; j <= 3; j++)
                {
                    row.Cells[j].Style.Add("background-color", "#DDDDDD");
                }
            }

            row.Cells[0].Attributes.Add("class", "textmode");
            row.Cells[1].Attributes.Add("class", "textmode");
            row.Cells[2].Attributes.Add("class", "textmode");
            row.Cells[3].Attributes.Add("class", "datetimemode");
        }

        // This line was causing some error and That's why this page's 'EnabledEventValidation' property set to "False"
        GridViewStatsLearnObjs.RenderControl(htmlWrite);

        //style to format numbers to string
        string style = "<style> .textmode { mso-number-format:\\@; } .percentmode { mso-number-format: Percent; } .datetimemode { mso-number-format: \" mm\\/dd\\/yyyy hh:mm:ss AM\\/PM\" } </style>";
        Response.Write(style);
        Response.Output.Write(stringWrite.ToString());
        Response.Flush();
        Response.End();

        GridViewStatsLearnObjs.PageSize = 200;
    }
}
